package cn.donghuapian.util;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @description:
 * @author: hzw
 * @time: 2024/9/27 13:30
 */
@Slf4j
public class CommonUtil {

    /**
     * 压缩图片
     *
     * @param originalFile 图片
     * @param format 图片格式：JPG,PNG
     * @param scale 压缩比例
     * @return
     * @throws IOException
     */
    public static byte[] compressImage(File originalFile, String format, double scale) throws IOException {
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(originalFile);

        // 计算新的宽度和高度
        int newWidth = (int) (originalImage.getWidth() * scale);
        int newHeight = (int) (originalImage.getHeight() * scale);

        // 创建新的图片
        BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, originalImage.getType());
        // 使用Graphics2D绘制缩小后的图片
        java.awt.Graphics2D g2d = resizedImage.createGraphics();
        g2d.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
        g2d.dispose();
        //转为byte数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(resizedImage, format, baos); // 将BufferedImage写入ByteArrayOutputStream
        baos.flush(); // 刷新流以确保所有数据都已写入
        byte[] imageInByteFormat = baos.toByteArray(); // 转换为byte数组
        baos.close(); // 关闭流
        return imageInByteFormat;
    }

}
